<!DOCTYPE html>

<head>
  <meta charset="UTF-8">
  <style>
    html,
    body,
    #map {
      height: 100%;
      width: 100%;
    }
    #list li{
      margin-right: 20px; 
      list-style: none;
      float: left;
    }

    #popup {
      height: 200px;
      width: 200px;
      margin-top: -200px;
      color: #fff;
      background: #253444b8;
    }

    #popup-closer {
      color: #fff;
    }
  </style>
  <title>一个最简单的例子</title>
  <link rel="stylesheet" href="../library/ol/ol.css">
  <link rel="stylesheet" href="../css/common.css">

  <script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.js"></script>

</head>

<body>
  <button id="start-animation">Start Animation</button>
  <button id="clear">clear</button>
  <button id="add">add</button>
  <button id="comeTo">come to</button>
  <input id="searchInput" type="text" placeholder="请输入搜索名" value="mark2">
  <button id="searchBtn">search</button>
  <ul id="list">
    <li class="mark1">mark1</li>
    <li class="mark2">mark2</li>
    <li class="mark3">mark3</li>
    <li class="mark4">mark4</li>
  </ul>

  <div id="popup" class="ol-popup">
    <a href="#" id="popup-closer" class="ol-popup-closer" onclick="()=>{$()}"> 关闭 </a>
    <div id="popup-content"></div>
  </div>
  <div id="map" class="map"> </div>


  <script src="../library/ol/ol-debug.js"></script>
  <script src="js/animation.js"></script>
  <script src="./js/common.js"></script>
  <script type="text/javascript">
    var vectorLayer = null;
    // 地图初始化
    var container = document.getElementById("popup");
    var content = document.getElementById("popup-content");
    var popupCloser = document.getElementById("popup-closer");
    var overlay = new ol.Overlay({
      //设置弹出框的容器
      element: container,
      //是否自动平移，即假如标记在屏幕边缘，弹出时自动平移地图使弹出框完全可见
      autoPan: true
    });
    //创建线样式
    var lineStyle = new ol.style.Style({
      stroke: new ol.style.Stroke({
        color: '#0f0',
        width: 6
      })
    });
    //创建矢量层
    var vectorSource = new ol.source.Vector({});
    var vectorLayer = new ol.layer.Vector({
      source: vectorSource,
      style: lineStyle
    });

    var extent = [0, 0, 0, 0]
    var map = new ol.Map({
      layers: [
        new ol.layer.Tile({
          source: new ol.source.OSM()
        })
      ],
      target: 'map',
      view: new ol.View({
        center: ol.proj.transform(
          [104, 30], 'EPSG:4326', 'EPSG:3857'),
        zoom: 6,
        minZoom: 4,
        // fit: extent
      })
    });
    var view = map.getView();
    // view.fit(extent);

    // debugger;

    /**
     * Add a click handler to hide the popup.
     * @return {boolean} Don't follow the href.
     */
    popupCloser.onclick = function () {
      overlay.setPosition(undefined);
      popupCloser.blur();
      return false;
    };

    addLayer()

    function addLayer() {
      console.log(overlay)
      // 开始
      $.ajaxSettings.async = true; //同步
      $.getJSON("./json/lines.json", function (points) {
        // debugger;
        // 获取弹出框
        var featureArr = []
        $.each(points.polygons, function (i, val) {
          var coords = val.points[0];
          console.log(val, coords)
          var Polygon = new ol.Feature({
            type: "LineString",
            geometry:  new ol.geom.LineString(coords),
            name: val.name,
            where: val.where
          });
          // debugger
          Polygon.setId(val.name)
          featureArr.push(Polygon)
        })
        //添加进map层
        map.addLayer(vectorLayer);
        console.log(vectorLayer)

        vectorSource.addFeatures(featureArr);
        // var feature = vectorSource.getFeatures()[0];
        // map.getView().setCenter(featureArr);
        map.on('click', function (e) {
          console.log(e)
          // view.setCenter(e.coordinate)
          //在点击时获取像素区域
          var pixel = map.getEventPixel(e.originalEvent);
          map.forEachFeatureAtPixel(pixel, function (feature) {
            var data = feature.getProperties();
            // var data2 = feature.getCoordinates();
            //coodinate存放了点击时的坐标信息
            var coodinate = e.coordinate;
            //设置弹出框内容，可以HTML自定义
            var text = "<span style='word-wrap:break-word'>你点击的坐标为：" + coodinate +
              "</span style='word-wrap:break-word'>";
            text += "<span style='word-wrap:break-word'>我的名字是：" + data.name +
              "</span style='word-wrap:break-word'>";
            text += "<span style='word-wrap:break-word'>我的名字是：" + data.where +
              "</span style='word-wrap:break-word'>";
            content.innerHTML = text;
            //设置overlay的显示位置
            overlay.setPosition(coodinate);
            //显示overlay
            map.addOverlay(overlay);
          });
        });
        // 移入feature鼠标手势
        map.on('pointermove', function (e) {
          var pixel = map.getEventPixel(e.originalEvent);
          var hit = map.hasFeatureAtPixel(pixel);
          if (hit) {
            map.getTargetElement().style.cursor = 'pointer';
          } else {
            map.getTargetElement().style.cursor = '';
          }
        });
      })
      // 结束
    }

    $("#add").click(function () {
      addLayer();
      map.removeLayer(vectorLayer);
    })
    $("#clear").click(function () {
      map.removeLayer(vectorLayer);
      overlay.setPosition(undefined);
    })
    $("#comeTo").click(function () {
      var a = vectorSource.getFeatures();
      // var b = a[1].get("name")
      // var c = a[1].getCoordinates()
      view.setCenter([0, 0])
    })
    $("#searchBtn").click(function () {
      // var a = vectorSource.getFeatures();
      var inputVal = $("#searchInput").val();
      var d = vectorSource.getFeatureById(inputVal)
      if (d) {
        var c = d.getProperties()
        var e = c.geometry.flatCoordinates;
        view.setCenter(e);
        view.setZoom(12);
      } else {
        alert("未搜索到对应内容")
      }
    })
    $("#list li").click(function () {
      var liVal = $(this).text();
      var d = vectorSource.getFeatureById(liVal)
      if (d) {
        var c = d.getProperties()
        var e = c.geometry.flatCoordinates;
        view.setCenter(e);
        // view.setZoom(12);
      } else {
        alert("未搜索到对应内容")
      }
    })
  </script>
</body>